import { login, logout, getInfo } from '@/api/login/login'
import {getToken, setToken, removeToken, setUserId, getUserId
  , setName, getName, removeName
  , setResources, getResources, removeResources
} from '@/utils/auth'
// import Cookies from 'js-cookie'

const user = {
  state: {
    token: getToken(),
    userId: getUserId(),
    name: getName(),
    avatar: '',
    roles: [],
    resources: getResources(),
    menu: [],
    routers: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      setToken(token)
    },
    SET_NAME: (state, name) => {
      state.name = name
      setName(name)
    },
    SET_USER_ID: (state, userId) => {
      state.userId = userId
      setUserId(userId)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_RESOURCES: (state, resources) => {
      state.resources = resources
      setResources(resources)
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
    },
    SET_ROUTERS: (state, routers) => {
      state.routers = routers
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      // const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response.data
          commit('SET_ROLES', data.role)
          commit('SET_RESOURCES', data.resource)
          commit('SET_NAME', data.uniqueName)
          commit('SET_MENU', data.menu)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut ({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          removeResources()
          // Cookies.remove('username')
          // Cookies.remove('access-token')
          removeToken()
          removeName()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
